﻿using System;
using System.Data.SqlClient;
using BikeBouncer.BusinessLayer.Entities;
using Devv.Core.UniDataTier;

namespace BikeBouncer.BusinessLayer
{
	public partial class DataAccess
	{
		#region Get

		public static SqlDataReader Address_Get(Int32 id)
		{
			DataHandler db = new DataHandler();

			db.AddParameter("@AddressId", id);

			return (SqlDataReader)db.ExecuteReader("upAddress_Get");
		}

		public static SqlDataReader Address_Get(City city)
		{
			DataHandler db = new DataHandler();

			db.AddParameter("@CityId", city.Id);

			return (SqlDataReader)db.ExecuteReader("upAddress_Get");
		}

		public static SqlDataReader Address_GetByPostcode(String postcode)
		{
			DataHandler db = new DataHandler();

			db.AddParameter("@Postcode", postcode);

			return (SqlDataReader)db.ExecuteReader("upAddress_Get");
		}
		
		public static SqlDataReader Address_GetByCountry(String country)
		{
			DataHandler db = new DataHandler();

			db.AddParameter("@Country", country);

			return (SqlDataReader)db.ExecuteReader("upAddress_Get");
		}

		#endregion

		#region Insert and update

		public static void Address_Upsert(Address address)
		{
			using (DataHandler db = new DataHandler())
			{
				if (address.City.Id < 1)
				{
					City_Upsert(address.City);
				}

				db.AddParameter("@CityId", address.City.Id, true); 
				db.AddParameter("@Postcode", address.Postcode, true);
				db.AddParameter("@Location", address.Location, true);
				db.AddParameter("@Phone", address.Phone, true);
				db.AddParameter("@Active", address.Active);

				if (address.Latitude != 0 && address.Longitude != 0)
				{
					db.AddParameter("@Latitude", address.Latitude, true);
					db.AddParameter("@Longitude", address.Longitude, true);
				}

				if (address.UserId > 0)
				{
					db.AddParameter("@UserId", address.UserId);
				}

				if (address.Id > 0)
				{
					db.AddParameter("@AddressId", address.Id);

					db.ExecuteScalar("upAddress_Update");
				}
				else
				{
					address.Id = Convert.ToInt32(db.ExecuteScalar("upAddress_Insert"));
				}
			}
		}

		#endregion
	}
}